
#include <iostream>

#include <mysql.h>

#include "db.h"
#include "lib_init.h"


// 检查表是否已存在
bool TableCreator::table_exists(const std::string& table_name) {
    std::string query = "SHOW TABLES LIKE '" + table_name + "'";
    db->accept(operater, query.c_str());
    if (!operater->IsOperationSuccess()) {
        std::cerr << "Error checking for table" << std::endl;
        return false;
    }

    uint64_t num_rows = operater->getQueryResult().second;
    return num_rows > 0;
}

// 创建表
void TableCreator::create_table(const std::string& table_name, const std::string& create_sql) {
    if (table_exists(table_name)) {
#ifdef DEBUG_PRINTS
        std::cout << "Table " << table_name << " already exists." << std::endl;
#endif
        return;
    }
    db->accept(operater, create_sql.c_str());
    if (operater->IsOperationSuccess()) {
#ifdef DEBUG_PRINTS
        std::cout << "Table " << table_name << " created successfully." << std::endl;
#endif
    }
}





bool LibraryTableCreator::LibarayTableInit() {
    std::string books_create_sql = R"(
        CREATE TABLE Books (
            ID VARCHAR(100),
            Title VARCHAR(255) NOT NULL,
            Author VARCHAR(100),
            Publisher VARCHAR(100),
            PublishDate DATE,
            Quantity INT,
            PRIMARY KEY (ID)
        );
    )";
    create_table("Books", books_create_sql);

    std::string purchases_create_sql = R"(
    CREATE TABLE Purchases (
        PurchaseID INT AUTO_INCREMENT,
        BookID  VARCHAR(100),
        Quantity INT,
        Date DATE,
        Price DECIMAL(10, 2), -- 价格最多有两位小数
        PRIMARY KEY (PurchaseID),
        FOREIGN KEY (BookID) REFERENCES Books(ID) ON DELETE CASCADE
        );
    )";
    create_table("Purchases", purchases_create_sql);

    std::string  discards_create_sql = R"(
    CREATE TABLE Discards (
        DiscardID INT AUTO_INCREMENT,
        BookID  VARCHAR(100),
        Quantity INT,
        Date DATE,
        PRIMARY KEY (DiscardID),
        FOREIGN KEY (BookID) REFERENCES Books(ID) ON DELETE CASCADE
        );
    )";
    create_table("Discards", discards_create_sql);

    std::string borrows_create_sql = R"(
    CREATE TABLE Borrows (
        BorrowID INT AUTO_INCREMENT,
        BookID  VARCHAR(100),
        UserID VARCHAR(100),
        BorrowDate DATE,
        ReturnDate DATE,
        Status ENUM('已借出', '已归还', '逾期未还') DEFAULT '已借出',
        PRIMARY KEY (BorrowID),
        FOREIGN KEY (BookID) REFERENCES Books(ID) ON DELETE CASCADE
        );
    )";
    create_table("Borrows", borrows_create_sql);

    return true;

}